<template>
  <div class="page_view">
    <div class="tabs_list">
      <!-- @tab-click="tabClick" -->
      <el-tabs type="border-card" v-model="curSmoke" @tab-click="tabClick" :before-leave="beforeLeave">
        <el-tab-pane v-for="(smoke) in smokeList" :key="smoke.allowanceId" :label="smoke.smokeName" :name="smoke.allowanceId"></el-tab-pane>
      </el-tabs>
    </div>

    <div class="page_title">
      <span>三点评吸详情</span>

      <div>
        <!-- :disabled="already != 2" -->
        <lay-button @click="setEditStatus" type="primary" v-if="system&& system.roles.includes('superadmin')  ">{{editStatus? "完成":"修改"}}</lay-button>
        <lay-button @click="close">关闭</lay-button>
      </div>
    </div>

    <div class="content">

      <!-- 用户列表 -->
      <div class="user_box">
        <div style="height: 38px;" v-if="smokeList.length>0"></div>
        <el-table :data="userList" border style="width: 100%;" height="65vh">
          <el-table-column prop="name" label="用户名" width="100" align="center" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="{row}">
              <el-button type="success" link @click="pushUser(row)" v-if="already!=2">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 烟支组合列表 -->
      <div class="smoke_box">
        <!-- <ul style="padding: 0 10px;" v-if="smokeList.length>0">
          <li>烟支A名称：{{ smokeList[0].smokeA }}</li>
          <li>烟支B名称：{{ smokeList[0].smokeB }}</li>
        </ul> -->

        <el-table :data="smokeComList" border style="width: 100%;" height="60vh">
          <el-table-column prop="index" label="序号" width="80" align="center" />
          <el-table-column prop="name" label="姓名" width="120" align="center">
            <template #default="{row}">
              <div :style="{color:row.workStatus==1?'#409eff':'red'}">
                {{row.name}}
              </div>
            </template>

          </el-table-column>
          <el-table-column prop="number" label="编号123" width="120" align="center" />
          <el-table-column prop="number" label="烟支A名称" width="200" align="center">
            <template #default>
              {{ smokeList[0].smokeA  }}
            </template>
          </el-table-column>

          <el-table-column prop="number" label="烟支B名称" width="200" align="center">
            <template #default>
              {{ smokeList[0].smokeB  }}
            </template>

          </el-table-column>
          <el-table-column prop="conclusion" label="评吸结论" min-width="210" align="center">
            <template #default="{row}">
              <!-- <span>{{ row }}</span>  -->
              <span v-if="!editStatus">{{ row.conclusion }}</span>
              <div v-if="editStatus && row.name && row.workStatus=='1'" class="edit_options_list">

                <span class="edit_options" :class="{'is_select': row.conclusion=='1=2'}" @click.stop="selectOptions(row, '1=2')">1=2</span>

                <span class="edit_options" :class="{'is_select': row.conclusion=='2=3'}" @click.stop="selectOptions(row, '2=3')">2=3</span>

                <span class="edit_options" :class="{'is_select': row.conclusion=='1=3'}" @click.stop="selectOptions(row, '1=3')">1=3</span>

              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="结果判断" align="center" width="120">
            <template #default="{row}">
              <span v-if="row.status===0||row.status==='0'"> √ </span>
              <span v-if="row.status===1||row.status==='1'"> × </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template #default="{row}">
              <el-button type="danger" link @click="removerUser(row)" v-if="row.name&&row.smokeStatus==0&&already!=2">移除</el-button>
              <el-button type="success" link @click="pushToUser(row)" v-if="row.name&&row.smokeStatus==0&&already!=2">推送</el-button>

              <el-button type="info" link v-if="row.name&&row.smokeStatus==1" :disabled="true">已推送</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="add_line">
          <div class="add_label">
            综合评价
          </div>
          <div class="add_value">
            <div>评吸人数：N= {{ form.smokeNumber }}</div>
            <div>混淆人数：M= {{ form.confoundNumber }}</div>
            <div>同质化率：M / N * 100%= {{ form.homogenizationRate }}%</div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, Ref, onMounted, onBeforeUnmount } from "vue";
import http from "@/http/index";
import { useRoute, useRouter } from "vue-router";
import { useCounterStore } from "@/current";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import { layer } from "@layui/layer-vue";

const router = useRouter();
const route = useRoute();
const mettingID = ref(route.query.mettingID);
const id = ref(route.query.id);
const meetingStatus = ref(route.query.status);
console.log(meetingStatus.value);

let queryStatus: any = route.query.status;
const already: Ref<string | number> = ref(queryStatus); //2表示已完成
const store = useCounterStore();
const { system } = storeToRefs(store); //  数据

// 烟支列表
let smokeList: Ref<Array<any>> = ref([]);
let curSmoke = ref("1");
let pointId = ""; //烟支的特殊id

// 用户列表
let userList: Ref<Array<any>> = ref([]);
//是否为编辑状态
let editStatus: Ref<Boolean> = ref(false);

// 烟的组合
let smokeComList: Ref<Array<any>> = ref([]);
// 循环获取烟支详情的定时器
let timer: any = null;
// 展示综合评价的信息
let form: Ref<any> = ref({});

onMounted(() => {
  getSmokeList();
});

onBeforeUnmount(() => {
  if (timer) {
    clearTimeout(timer);
  }
});

// 设置修改状态
function setEditStatus() {
  editStatus.value = !editStatus.value;

  // if (editBtn.value) {
  //   clearInterval(timer.value);
  // } else {
  //   startTimer();
  // }
}

// 修改选项
async function selectOptions(row: any, value: string) {
  console.log(row, value);
  row.conclusion = value;
  const res: any = await http.corsApi(`/smokeMeeting/threePoint`, "put", {
    ...row,
    pointId,
  });
  if (res.code == 200) {
    ElMessage.success("修改成功");
  }

  await getSmokeDetial();
}

// 获取烟支列表
async function getSmokeList() {
  const res: any = await http.corsApi(`/smokeMeeting/threePointSmoke/${id.value}`, "get", {});
  console.log(res);
  if (res.code != 200) return;

  smokeList.value = res.data || [];
  if (smokeList.value.length > 0) {
    curSmoke.value = smokeList.value[0].allowanceId;
    pointId = smokeList.value[0].pointId;
    initSmokeComList();
    getSmokeDetial();
    getUserList();
  }
}

// 循环获取烟支详情
async function getSmokeDetial(reset = false) {
  if (timer) {
    clearTimeout(timer);
  }
  const res = await http.corsApi("/smokeMeeting/threePointDetails", "get", { id: route.query.id, allowanceId: curSmoke.value });

  if (reset) {
    initSmokeComList();
  }

  let a = res.data.find((ele: any) => {
    return ele.name;
  });
  if (a) {
    form.value = a;
  }

  mergeSmokeList(res.data || []);

  timer = setTimeout(() => {
    if (meetingStatus.value == "2") {
      return false;
    }
    getSmokeDetial();
    getUserList();
  }, 1000 * 5);
}

function mergeSmokeList(list: Array<any>) {
  console.log(list);

  list.forEach((ele) => {
    // console.log(ele.number);

    let index = smokeComList.value.findIndex((item) => {
      return ele.sort === item.sort;
    });
    console.log(index);

    if (index > -1) {
      smokeComList.value[index] = { ...ele, index: index + 1 };

      // console.log(smokeComList.value[index]);
    }
  });

  console.log(smokeComList.value);
}

// 初始化烟支详情
function initSmokeComList() {
  const coms = ["BAA", "ABA", "AAB", "ABB", "BAB", "BBA", "BAA", "ABA", "AAB", "ABB", "BAB", "BBA", "BAA", "ABA", "AAB", "ABB", "BAB", "BBA", "BAA", "ABA"];
  let list: Array<any> = [];
  coms.forEach((ele, index) => {
    list.push({
      id: index,
      index: index + 1,
      name: "",
      userId: "",
      number: ele, //编号
      allId: mettingID.value, // 会议id
      workStatus: 0, // 完成状态
      allowanceId: curSmoke.value, //烟支id
      conclusion: "", //评吸结论
      smokeStatus: 0, // 推送状态 0未推送
      status: "", //结果判定 0正常, 1 失败
      sort: index + 1,
    });
  });
  smokeComList.value = list;

  console.log(smokeComList.value);
}

// 获取用户列表
async function getUserList() {
  const res = await http.corsApi(`/meetingThreePoint/getMeetingUser`, "get", {
    meetingId: mettingID.value,
    pointId: pointId,
  });

  console.log("获取到的用户列表", res);

  userList.value = res.data || [];
}

// 添加用户到分配表
async function pushUser(row: any) {
  console.log("推送的行", row);
  let a = smokeComList.value.find((ele) => {
    return !ele.name;
  });
  console.log(a);

  if (!a) {
    return ElMessage.warning("没有可推送的组合了！");
  }
  const res: any = await http.corsApi(`/meetingThreePoint/editUserThreePoint`, "put", {
    number: a.number,
    pointId: pointId,
    sort: a.index,
    userId: row.userId,
  });
  console.log("推送的结果为", res);
  if (res.code == 200) {
    ElMessage.success("添加成功");
  }
  getSmokeDetial(true);
  getUserList();
}

// 推送给用户
async function pushToUser(row: any) {
  console.log(row);

  if (!row.name) return;
  const res: any = await http.corsApi(`/meetingThreePoint/meetingThreePushUser`, "put", {
    allowanceId: curSmoke.value,
    pointId: pointId,
    userids: [row.userId],
    // meetingId:mettingID.value,
    allId: row.allId,
  });
  if (res.code == 200) {
    ElMessage.success("推送成功");
  }
  getSmokeDetial(true);
}

// 移除用户至人员库
async function removerUser(row: any) {
  if (!row.name) {
    return;
  }
  const res: any = await http.corsApi(`/meetingThreePoint/deleteOne/${row.id}`, "delete", {});
  if (res.code == 200) {
    ElMessage.success("移除人员至人员库成功");
  }
  getSmokeDetial(true);
  getUserList();
}

// function tabClick(item: any) {
//   console.log(curSmoke.value);
//  console.log(item);

//   if(editStatus.value){
//     layer.msg('修改状态不能切换',{icon:2})
//     return false
//   }
//   // console.log("点击的对象", props)
//   curSmoke.value = item.name;
//   const a = smokeList.value.find((ele) => {
//     return ele.allowanceId == curSmoke.value;
//   });
//   if (!a) {
//     console.log("没有找到对应的烟支信息");
//     return;
//   } else {
//     console.log("点击的烟支", a);
//   }
//   pointId = a.pointId;

//   clearTimeout(timer);
//   getSmokeDetial(true);
//   getUserList();
// }

const beforeLeave = async (to, from, done) => {
  return new Promise((resolve, reject) => {
    // 异步操作...
    if (editStatus.value) {
      reject(); // 拒绝 Promise，阻止切换
    } else {
      resolve(true); // 解决 Promise，允许切换
    }
  });
};
function tabClick({ props }: any) {
  console.log(curSmoke.value);
  console.log(props);
  if (editStatus.value) {
    layer.msg("修改状态不能切换", { icon: 2 });
    return false;
  }
  // console.log("点击的对象", props)
  curSmoke.value = props.name;
  const a = smokeList.value.find((ele) => {
    return ele.allowanceId == curSmoke.value;
  });
  if (!a) {
    console.log("没有找到对应的烟支信息");
    return;
  } else {
    console.log("点击的烟支", a);
  }
  pointId = a.pointId;

  clearTimeout(timer);
  getSmokeDetial(true);
  getUserList();
}

function close() {
  router.go(-1);
}
</script>

<style scoped lang="scss">
.page_view {
  width: 100%;
  .page_title {
    font-size: 28px;
    font-weight: 600;
    color: #1f1f1f;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .edit_options_list {
    display: flex;
    align-items: center;
    justify-content: center;
    .edit_options {
      display: block;
      padding: 4px 12px;
      margin: 0 10px;
      border: 1px solid #ddd;
      font-size: 14px;
      border-radius: 2px;
      cursor: pointer;
    }
    .is_select {
      border: 1px solid #51f01c;
    }
  }
}

.content {
  width: 100%;
  box-sizing: border-box;
  padding: 0 20px;
  position: relative;
  .user_box {
    width: 200px;
  }
  .smoke_box {
    width: calc(100% - 300px);
    position: absolute;
    top: 0;
    right: 20px;
    .add_line {
      box-sizing: border-box;
      width: 100%;
      display: flex;
      align-items: center;
      background-color: #fff;
      .add_label {
        width: 79px;
        min-height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .add_value {
        border-left: 1px solid #ebeef5;
        flex: 1;
        padding: 10px;
        padding-left: 20px;
        line-height: 24px;
      }
    }
  }
}

:deep(.el-tabs__content) {
  display: none;
}
</style>